﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace Adams.Admin.DataAccess.Security
{
    public static class Login
    {
        public static Adams.Admin.DataTransfer.Security.Login.UserInfo GetUserInfo(string email)
        {
            var data = new Adams.Admin.DataTransfer.Security.Login.UserInfo();

            using (SqlDataReader dr = DB.RunDataReader(@"
SELECT *
FROM Console.Users
WHERE Email = @Email
", CommandType.Text,
                DB.CreateParameter("@Email", email, SqlDbType.VarChar, 50)))
            {
                if (dr.HasRows)
                {
                    dr.Read();
                    data.UserID = dr["UserID"].DbInt();
                    data.PasswordHash = dr["PasswordHash"].DbString();
                    data.PasswordSalt = dr["PasswordSalt"].DbString();
                    data.IsActive = dr["IsActive"].DbBool();
                    data.LastLoginAttempt = dr["LastLoginAttempt"].DbDate();
                    data.FailedLoginAttempts = dr["FailedLoginAttempts"].DbInt();
                    data.Exists = true;
                }
                else
                {
                    data.Exists = false;
                }
            }

            return data;
        }

        public static void ClearLockout(int userId)
        {
            DB.Run(@"
UPDATE Console.Users SET 
FailedLoginAttempts = 0, LastLoginAttempt = GETUTCDATE()
WHERE UserID = @UserID
", CommandType.Text,
                DB.CreateParameter("@UserID", userId, SqlDbType.Int));
        }

        public static void UpdateLockout(int userId)
        {
            DB.Run(@"
UPDATE Console.Users SET 
FailedLoginAttempts = (FailedLoginAttempts + 1), LastLoginAttempt = GETUTCDATE()
WHERE UserID = @UserID
", CommandType.Text,
                    DB.CreateParameter("@UserID", userId, SqlDbType.Int));
        }
    }
}
